//#ifdef H5
import jweixin from 'jweixin-module'
//#endif

export function scan(scanType = ['qrCode', 'barCode'], onlyFromCamera = true) {
  return new Promise(async (resolve, reject) => {
    //#ifdef APP-PLUS || MP-WEIXIN
    // 允许从相机和相册扫码
    uni.scanCode({
      onlyFromCamera,
      scanType,
      success: (res) => resolve(res),
      fail: (res) => {
        uni.showToast({
          title: '扫码失败!',
          icon: 'none',
          duration: 2000,
        })
        reject(res)
      },
    })
    //#endif

    //#ifdef H5
    jweixin.ready(function () {
      jweixin.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
        scanType, // 可以指定扫二维码还是一维码，默认二者都有
        success: (res) => {
          const obj = {
            // 统一成一样的结果 resultStr: 'en109,23324234234234'
            result: res.resultStr.split(',').pop(),
            errMsg: res.errMsg === 'scanQRCode:ok' ? 'scanCode:ok' : 'scanCode:fail',
          }
          resolve(obj)
        },
        fail: (err) => reject(err),
      })
    })
    //#endif
  })
}
